clear
capture restore
set scheme cleanplots, perm

* SET DIRECTORIES
global home "..."

global data "$home/Data/"
global output "$home/Output/"

cd $home

*SET CONTROL VARIABLES
local firm_controls "log_salesg_real_1lag_std size_assets_1lag_std liquidity_1lag_std pcmq_1lag_std recpay2yq_1lag_std d2aq_1lag_std ln_market_cap_q_1lag_std tobins_q_1lag_std lev_d2c_1lag_std dd_1lag_std age_1lag_std i.sector i.fqtr"

local agg_controls "lngdp inflation unemp nasdaq fedfunds"

*************
***Options***
*************
*Set ivol measure to use as baseline
local matur m1545
*Set mp shock to use as baseline
local mps ff4_d

* Set the LP details ========================================================================
*# periods to compute the responses foreach
local hor = 20
*# lags of "endogenous" variables 
local lagy = 4 
*# lags of "shock"
local lage = 0 

local mps_ints "c.`mps'#c.log_salesg_real_1lag_std c.`mps'#c.size_assets_1lag_std c.`mps'#c.liquidity_1lag_std c.`mps'#c.pcmq_1lag_std c.`mps'#c.recpay2yq_1lag_std c.`mps'#c.d2aq_1lag_std c.`mps'#c.ln_market_cap_q_1lag_std c.`mps'#c.tobins_q_1lag_std c.`mps'#c.lev_d2c_1lag_std c.`mps'#i.sector c.`mps'#i.fqtr c.`mps'#c.age_1lag_std c.`mps'#c.dd_1lag_std"

********************************************************************************
********************************************************************************
********************************************************************************
*Read-in ivol data (contains all trading days for Compustat firms)
use "${data}Compustat_Quarterly_Final", clear

local n = 20

*Set panel data
xtset firmid ts_qtr

*Flag sample for those in at least n quarters
bysort gvkey pre_crisis: egen obs_num_temp = count(gvkey) if pre_crisis
bysort gvkey: egen obs_num = max(obs_num_temp)

*Flag outliers (bottom/top 0.5%) for investment
_pctile investment_intensive if pre_crisis, p(.5 99.5)
gen 	investment_outlier = (investment_intensive<r(r1)|investment_intensive>r(r2))

***
*Calculate recent sales volatility (3-year rolling window)
bysort firmid: asrol log_salesg_real, stat(sd) window(ts_qtr -12 -1) gen(sales_volatility)
*Winsorize 1% tails
sum sales_volatility, detail
gen 	sales_volatility_wins = sales_volatility
replace sales_volatility_wins = r(p1) if sales_volatility_wins<r(p1)
replace sales_volatility_wins = r(p99) if sales_volatility_wins>r(p99) & !missing(sales_volatility_wins)
***

gen sample_period=(pre_crisis==1)

gen in_sample = (obs_num>=`n' & !missing(obs_num) & investment_outlier==0 & sample_period)

********************************************************************************
*Set panel data
xtset firmid ts_qtr

gen ivol_`matur'_std = ivol_`matur'
gen dd_std = dd
gen age_1lag_std = age

rename age age_1lag

***Standardize quarterly Compustat variables and lagged ivol level
foreach i in dd_1lag age_1lag log_salesg_real_1lag size_assets_1lag liquidity_1lag pcmq_1lag recpay2yq_1lag d2aq_1lag ln_market_cap_q_1lag tobins_q_1lag lev_d2c_1lag ivol_`matur'  {

	*Pre-Crisis Standardization
	drop `i'_std
	qui: sum `i' if in_sample
	gen `i'_std = (`i' - r(mean)) / r(sd)
	
}

*Standardize ivol and dd
_pctile ivol_`matur' if pre_crisis, percentiles(30 70)
gen ivol_`matur'_hi2lo = (ivol_`matur' - r(r1)) / (r(r2) -  r(r1))

_pctile dd  if in_sample, percentiles(30 70)
gen dd_hi2lo = (dd - r(r1)) / (r(r2) -  r(r1))

_pctile sales_volatility_wins if pre_crisis, percentiles(30 70)
gen svol_hi2lo = (sales_volatility_wins - r(r1)) / (r(r2) -  r(r1))

*Standardize mps to unit standard deviation & positive is contracionary
gen `mps'=`mps'_shock_qtr
egen date_tag=tag(ts_qtr)

sum `mps' if pre_crisis & date_tag
replace `mps' = `mps'/r(sd)
********************************************************************************
*Prepare local projection variables
********************************************************************************
xtset firmid ts_qtr

*Use the inflation-adjusted versions of dependent variables, if applicable
foreach i in niq K_int_Org {
	
	drop `i'
	rename `i'_real `i'
 
}


foreach var in capital_stock K_int_Org_qtr {
	forvalues h =   0/`hor' {
		 gen `var'`h' = (ln(f`h'.`var') - ln(l.`var')) * 100
}
}

*Create time variable for DK SEs
xtset
egen time=group(ts_qtr)
xtset firmid time

drop if !in_sample

********************************************************************************
*4. Use Sales Volatility instead of ivol
********************************************************************************
	foreach var in capital_stock K_int_Org_qtr { 
	
	eststo clear
		
	cap gen qtrs = _n-1 if _n<=`hor'+1
	cap gen zero =  0 	if _n<=`hor'+1
	cap gen b_mps = 0
	cap gen u_mps = 0
	cap gen d_mps = 0

	cap gen b_ivol = 0
	cap gen u_ivol = 0
	cap gen uu_ivol = 0 
	cap gen d_ivol = 0
	cap gen dd_ivol = 0

	cap gen b_mpsI = 0
	cap gen u_mpsI = 0
	cap gen uu_mpsI = 0
	cap gen d_mpsI = 0
	cap gen dd_mpsI = 0

	cap gen b_intEff = 0

	cap gen nobs = 0
	
	********************************************************************************
	*INVESTMENT REGRESSIONS
	********************************************************************************

	forvalues h = 0/`hor' {

		quietly: reghdfe `var'`h' `mps' L.svol_hi2lo  c.`mps'#c.L.svol_hi2lo `firm_controls' l(1/`lagy').(`agg_controls') if in_sample, a(firmid) vce(cluster time,dkraay(16)) old

		replace b_mpsI = _b[c.`mps'#c.L.svol_hi2lo ]                     			if _n == `h'+1
		replace u_mpsI = _b[c.`mps'#c.L.svol_hi2lo ] + 1.645* _se[c.`mps'#c.L.svol_hi2lo ]  	if _n == `h'+1
		replace d_mpsI = _b[c.`mps'#c.L.svol_hi2lo ] - 1.645* _se[c.`mps'#c.L.svol_hi2lo ]  	if _n == `h'+1	
		replace uu_mpsI = _b[c.`mps'#c.L.svol_hi2lo ] + _se[c.`mps'#c.L.svol_hi2lo ]  	if _n == `h'+1
		replace dd_mpsI = _b[c.`mps'#c.L.svol_hi2lo ] - _se[c.`mps'#c.L.svol_hi2lo ]  	if _n == `h'+1			
		replace nobs = e(N)                        						if _n == `h'+1	
		di e(N)
		eststo
		
	}

	* Plot the Investment response
	twoway (rarea u_mpsI d_mpsI qtrs, fcolor(gs14) lcolor(gs14) lw(none) lpattern(solid) xlabel(,labsize(medlarge) nogrid) ylabel(,labsize(medlarge) nogrid)) ///
	(rarea uu_mpsI dd_mpsI qtrs, fcolor(gs8) lcolor(gs8) lw(none) lpattern(solid)) ///
	(line b_mpsI qtrs, lcolor(black) lpattern(solid) lwidth(thick)) /// 
	(line zero qtrs, lcolor(black)) if !missing(qtrs), legend(off) ///
	ytitle("Percent", size(medlarge)) xtitle("Quarter", size(medlarge)) ///
	graphregion(color(white)) plotregion(color(white))

	graph export "${output}figureA10_`var'.pdf", replace
	
	drop qtrs zero b_mps u_mps d_mps b_ivol u_ivol d_ivol b_mpsI u_mpsI uu_mpsI d_mpsI dd_mpsI b_intEff uu_ivol dd_ivol nobs
	
	eststo clear	
}

